package com.ruowei.modules.wxpay.service;

import com.ruowei.modules.wxpay.domain.RefundFailedRecord;
import com.ruowei.modules.wxpay.domain.WeChatPayReturn;
import com.ruowei.modules.wxpay.domain.enumeration.PayReturnType;
import com.ruowei.modules.wxpay.repository.RefundFailedRecordRepository;
import com.ruowei.modules.wxpay.repository.WeChatPayReturnRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;

@Service
@Slf4j
public class PayReturnService {

    private final WeChatPayReturnRepository returnRepository;
    private final RefundFailedRecordRepository recordRepository;

    public PayReturnService(WeChatPayReturnRepository returnRepository, RefundFailedRecordRepository recordRepository) {
        this.returnRepository = returnRepository;
        this.recordRepository = recordRepository;
    }

    public void saveReturnData(String orderCode, String orderReturnCode, String jsonData, PayReturnType type) {
        WeChatPayReturn payReturn = new WeChatPayReturn();
        payReturn.setOrderCode(orderCode);
        payReturn.setOrderRerunCode(orderReturnCode);
        payReturn.setTime(Instant.now());
        payReturn.setJsonData(jsonData);
        payReturn.setType(type);
        payReturn.setDate(LocalDate.now());
        returnRepository.save(payReturn);
    }

    public void saveFailedRecord(String orderCode, String orderReturnCode, BigDecimal amount,
                                 String returnMsg, String resultCode, String errCode, String errCodeDes,
                                 String transactionId, String refundId) {
        RefundFailedRecord record = new RefundFailedRecord();
        record.setOrderCode(orderCode);
        record.setOrderRerunCode(orderReturnCode);
        record.setAmount(amount);
        record.setReturnMsg(returnMsg);
        record.setResultCode(resultCode);
        record.setErrCode(errCode);
        record.setErrCodeDes(errCodeDes);
        record.setTransactionId(transactionId);
        record.setRefundId(refundId);
        record.setTime(Instant.now());
        record.setStatus(false);
        recordRepository.save(record);
    }
}
